package com.example.supermarket.service;

import com.example.supermarket.entity.Member;
import com.example.supermarket.mapper.MemberMapper;
import com.example.supermarket.mapper.OrderMapper;
import com.example.supermarket.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * <p>会员模块服务层</p>
 * @author Bosen
 * @date 2021/10/12 14:14
 */
@Service
public class MemberHomeService {

    @Autowired
    MemberMapper memberMapper;
    @Autowired
    OrderMapper orderMapper;

    /**
     * <p>检查登录信息是否正确</p>
     * @param name 用户昵称
     * @param password 密码
     */
    public boolean checkLoginInfo(HttpServletRequest request, String name, String password) {
        // 通过名字获取会员信息
        Member member = memberMapper.findInfoByName(name);
        if (member == null) {
            return false;
        }
        // 密码匹配返回true，否则返回false
        if (member.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            // 使用session存储登录信息
            request.getSession().setAttribute("member", member);
            return true;
        }
        return false;
    }

    /**
     * <p>退出登录</p>
     */
    public void logout(HttpServletRequest request) {
        request.getSession().setAttribute("member", null);
    }

    /**
     * <p>会员下单</P>
     * @Date 2021/10/13 22:18
     * id 商品id
     *
     */
    public int order(HttpServletRequest request, int id, int payStatus){
        //随机生成订单id
        String orderId = "O"+ new Random().nextInt(999999-100000)+100000+ DateUtil.getNMDHIS();
        request.getSession().setAttribute("orderId",orderId);
        //获取会员信息
        Member member =(Member) request.getSession().getAttribute("member");
        int memberId = member.getId();
        return orderMapper.insert(id, memberId,payStatus, orderId, System.currentTimeMillis());



    }
}
